package com.gonsin.venus.sdk.client;

import com.gonsin.venus.sdk.exceptions.ApiException;
import com.gonsin.venus.sdk.exceptions.ErrorCodes;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

@Slf4j
public class GonsinHttpClient extends CloseableHttpClient {

    private CloseableHttpClient clientProxy;

    public GonsinHttpClient(){

    }


    @Override
    protected CloseableHttpResponse doExecute(HttpHost target, HttpRequest request, HttpContext context) throws IOException, ClientProtocolException {
        if(token == null){
            CloseableHttpClient client = HttpClientBuilder.create().build();

            String host = target.getHostName();
            String token = getToken(target);
            try {

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    private String getToken(HttpHost target) {
        TokenBo token = TokenManager.getInstance().get(host);
        if(token != null){
            return token.getXToken();
        }

        HttpGet httpGet = new HttpGet(config.toUrl(url));
        HttpResponse response = clientProxy.execute(httpGet);
        if(response.getStatusLine().getStatusCode() != 200){
            throw new ApiException(ErrorCodes.HTTP_ERROR, "获取Token失败");
        }
        InputStream input = response.getEntity().getContent();

        StringBuilder sb = new StringBuilder();
        String line;
        BufferedReader br = new BufferedReader(new InputStreamReader(input));
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        String str = sb.toString();

        log.info(str);

        JsonElement element = JsonParser.parseString(str);
        JsonObject responseJson = element.getAsJsonObject();
        int status = responseJson.get("state").getAsInt();
        if(status != 200){
            throw new ApiException(ErrorCodes.TOKEN_ERROR, "获取Token失败");
        }

        JsonObject dataJson = responseJson.get("data").getAsJsonObject();
        long expireTime = dataJson.get("expireTime").getAsLong();
        String xToken = dataJson.get("xtoken").getAsString();

        token = new TokenBo();
        token.setXToken(xToken);
        token.setExpireTime(expireTime);
        return token.getXToken();
    }

    @Override
    public void close() throws IOException {
        this.clientProxy.close();
    }

    @Override
    public HttpParams getParams() {
        return clientProxy.getParams();
    }

    @Override
    public ClientConnectionManager getConnectionManager() {
        return clientProxy.getConnectionManager();
    }
}
